﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using MassPokerTool.Infrastructure.Hooking.Data;

namespace MassPokerTool.Infrastructure.Hooking.Filters
{
    public class PokerStarsChatEndPaintHookFilter : IEndPaintFilter
    {
        public bool Match(int hWnd, ref PlatformInvoke.Paintstruct lpPaint, out IHookData hookData)
        {
            hookData = new PokerStarsChatEndPaintHookData();
            var className = new StringBuilder(100);
            PlatformInvoke.GetClassName(new IntPtr(hWnd), className, className.Capacity);
            if (className.ToString() != "PokerStarsChatClass")
                return false;
            var parentHWnd = PlatformInvoke.GetParent(new IntPtr(hWnd));
            var windowText = new StringBuilder(100);
            PlatformInvoke.GetWindowText(parentHWnd, windowText, windowText.Capacity);
            var bmp = CaptureWindow(new IntPtr(hWnd));
            byte[] byteArray;
            using (var ms = new MemoryStream())
            {
                bmp.Save(ms, ImageFormat.Bmp);
                byteArray = ms.ToArray();
            }
            hookData = new PokerStarsChatEndPaintHookData()
                           {
                               ClassName = className.ToString(),
                               WindowName = windowText.ToString(),
                               SerializedBmp = byteArray
                           };
            return true;
        }

        private Bitmap CaptureWindow(IntPtr hWnd)
        {
            var rctForm = Rectangle.Empty;
            using (var grfx = Graphics.FromHdc(PlatformInvoke.GetWindowDC(hWnd)))
            {
                rctForm = Rectangle.Round(grfx.VisibleClipBounds);
            }
            var pImage = new Bitmap(rctForm.Width, rctForm.Height);
            var graphics = Graphics.FromImage(pImage);
            var hDc = graphics.GetHdc();
            try
            {
                PlatformInvoke.PrintWindow(hWnd, hDc, (uint)0);
            }
            finally
            {
                graphics.ReleaseHdc(hDc);
            }
            return pImage;
        }
    }
}
